package com.kabuda.zhugehot200;

/**
 * @author kabuda
 * @date 2025-03-15 18:12
 * @description
 */
public class t206_反转链表 {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int val) {
            this.val = val;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }

    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        listNode1.next = listNode2;
        listNode2.next = listNode3;

        //System.out.println(iteration(listNode1));
        System.out.println(recursion(listNode1));
    }

    /**
     * 迭代解法
     *
     * @param head
     * @return
     */
    public static ListNode iteration(ListNode head) {
        ListNode pre = null, next, cur;
        cur = head;
        while (cur != null) {
            //把下一个存起来
            next = cur.next;
            //处理下一个，反向指向
            cur.next = pre;
            pre = cur;
            cur = next;
        }

        return pre;
    }

    /**
     * 递归揭发
     *
     * @param head
     * @return
     */
    public static ListNode recursion(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode recursion = recursion(head.next);
        head.next.next = head;
        head.next = null;
        return recursion;
    }
}
